<template>
	<view>
		<u-navbar class="navbar" :border-bottom="false" title="结算订单" :title-size="36" :title-bold="true"
			:title-color="textColor" :background="{backgroundColor: '#fff'}">
		</u-navbar>
		<view class="u-p-35 u-m-b-20" style="background-color: #fff;" v-show="sendData.settlementMethod === 1">
			<process-used @sendAdequate="getAdequateFn" :sellerId="settlementInfo.sellerShopId" :buyerId="storeShop.id" :totalPrice="actualAmount"></process-used>
		</view>
		<!-- 地址 -->
		<ak-address class="u-m-b-20" :address="addressInfo"></ak-address>
		<!-- 是否开票 -->
		<!-- <u-cell-group class="u-m-b-20">
			<u-cell-item title="立刻开票" :arrow="false" :border-bottom="false">
				<u-switch slot="right-icon" v-model="isInvoice" :size="40" :active-color="themeColor"
					:inactive-color="greyColor" @change="changeIsInvoice"></u-switch>
			</u-cell-item>
		</u-cell-group> -->
		<!-- 电子发票 -->
		<!-- <u-cell-group v-if="isInvoice" class="u-m-b-20">
			<u-cell-item title="电子发票" :arrow="false" :border-bottom="false">
				<u-switch slot="right-icon" v-model="isElectronic" :size="40" :active-color="themeColor"
					:inactive-color="greyColor"></u-switch>
			</u-cell-item>
		</u-cell-group> -->
		<!-- 发票信息 -->
	<!-- 	<ak-invoice class="u-m-b-20" v-if="isInvoice" :is-electronic="isElectronic" :isChange="true" :invoice="invoice"
			@changeInvoice="changeisProfessional"></ak-invoice> -->
		<!-- 订单信息 -->
		<view class="box-color box-padding u-m-b-20">
			<view class="u-font-30 u-m-b-30">
				{{ settlementInfo.sellerShopName }}
			</view>
			<view v-for="(item, index) in settlementInfo.shoppingCartItems" :key="index" class="item u-flex u-m-b-20">
				<image :src="item.url" style="width: 180rpx;height: 180rpx;border-radius: 10rpx;"
					mode=""></image>
				<view class="u-flex-col u-row-between u-flex-1 u-m-l-20" style="height: 180rpx">
					<view class="u-flex u-row-between u-m-b-20">
						<text class="u-font-28">{{ item.itemName }}</text>
						<text class="u-font-32">￥{{ item.price }}</text>
					</view>
					<view class="u-flex u-row-between">
						<view class="grey-box">
							{{ item.specification }}
						</view>
						<view class="grey-box">
							x{{ item.quantity }}
						</view>
					</view>
					<view style="height: 70rpx;"></view>
				</view>
			</view>
		
			<view class="u-border-bottom"></view>
			<view class="u-flex u-row-between u-p-t-30">
				<text class="u-font-32 text-bold">总价</text>
				<text :style="{fontSize: '40rpx'}">￥{{ settlementInfo.total }}</text>
			</view>
		</view>
		<!-- 优惠 -->
		<u-cell-group class="u-m-b-20">
			<u-cell-item :value="(promotionFree===0&&giftList.length===0)?'选择':'-￥'+promotionFree" :border-bottom="false" 
			:value-style="valueStyle" @click="showActive"
				>
				<!-- v-if="promotionList.length!=0" -->
				<template #title>
					<view  class="u-flex">
						<image src="/static/order/huodong.png" style="width: 40rpx;height:36rpx;" mode=""></image>
						<text class="u-m-l-14">活动</text>
						<text class="u-m-l-10 u-font-26" v-if="promotionIdList.length!=0" style="color: #999;max-width: 400rpx;overflow: hidden;">
							已选择{{promotionIdList.length}}个活动
							</text>
					</view>
				</template>
				
				
			</u-cell-item>
			<view class="u-p-l-35 u-p-r-35 u-p-b-20" v-if="giftList.length!=0">
				<view v-for="(item, index) in giftList" :key="index" class="item u-flex u-m-b-20">
					<view class="" style="position: relative;">
						<image :src="item.url" style="width: 120rpx;height: 120rpx;border-radius: 10rpx;"
							mode=""></image>
						<image src="/static//order/giftMarkTop.png" mode="" style="position: absolute;top: 0;left:0;width: 64rpx;height: 64rpx;"></image>
					</view>
					<view class="u-flex-col u-row-between u-flex-1 u-m-l-20" >
						<view class="u-flex u-row-between u-m-b-20">
							<text class="u-font-28">{{ item.itemName }}</text>
							<text class="u-font-32">￥{{ item.price }}</text>
						</view>
						<view class="u-flex u-row-between">
							<view class="grey-box">
								{{ item.specification }}
							</view>
							<view class="grey-box">
								x{{ item.quantity }}
							</view>
						</view>
					</view>
				</view>
			</view>
		</u-cell-group>
		<!-- <u-cell-group class="u-m-b-20">
			<u-cell-item :value="'-￥' + couponAmount" :border-bottom="false" :value-style="valueStyle" @click="showCoupon">
				<view slot="title" class="u-flex">
					<image src="/static/order/youhuiquan.png" style="width: 40rpx;height:36rpx;" mode=""></image>
					<text class="u-m-l-14">优惠券</text>
				</view>
			</u-cell-item>
		</u-cell-group>-->
		<u-cell-group class="u-m-b-20">
			<u-cell-item :value=" redBalance===0?'去使用':('-￥'+redBalance) " :border-bottom="false" :value-style="valueStyle" @click="showBalance">
				<template #title>
					<view  class="u-flex">
						<image src="/static/order/zhanghuyue.png" style="width: 40rpx;height:36rpx;" mode=""></image>
						<text class="u-m-l-14">账户余额</text>
					</view>	
				</template>
				
			</u-cell-item>
		</u-cell-group> 
		<u-cell-group class="u-m-b-20">
			<u-cell-item :value="postFee" :border-bottom="false" :arrow="false" :value-style="valueStyle">
				<template #title>
					<view class="u-flex">
						<image src="/static/order/yunfei.png" style="width: 40rpx;height:36rpx;" mode=""></image>
						<text class="u-m-l-14">运费</text>
						<text class="grey-color u-font-26 u-m-l-20" v-if="postFeeInfo.baseValue !=0 || postFeeInfo.freeDeliveryValue!=0||postFeeInfo.freeShippingValue!=0" @click="showPostFee"><u>查看运费规则</u></text>
					</view>	
				</template>
				
			</u-cell-item>
		</u-cell-group>
		<view class="box-padding-col u-flex"
			style="background-color: #FFFFFF;height: 114rpx; margin-bottom: 40rpx;line-height: 114rpx;">
			<image src="/static/order/beizhu.png" style="width: 40rpx;height:36rpx;" mode=""></image>
			<text class="u-m-l-14">备注</text>
			<uni-easyinput style="margin-left: 20rpx;" :autoHeight="true" v-model="remarks" type="textarea"
				placeholderStyle="line-height:50rpx" placeholder="请输入备注" />
		</view>
		
		<!-- 占位盒子 -->
		<view style="height: 255rpx;"></view>
		<!-- <view style="height: 290rpx;"></view> -->
		<!-- footer -->
		<view class="footer">
			<view class="u-flex u-row-between box-padding-col" style="height: 114rpx;">
				<text class="u-font-32 text-bold">实付款</text>
				<text :style="{fontSize: '40rpx', color: badgeColor}">￥{{ actualAmount }}</text>
			</view>
			<view class="box-padding-col u-p-b-50" style="height: 140rpx;">
				<u-button shape="circle" hover-class="none" :ripple="true" :hair-line="false"
					:custom-style="getBtStyle('default', -1, 90, 28)" v-if="sendData.isAdequate||sendData.settlementMethod === 0" @click="handleSubmit">提交订单</u-button>
					<u-button shape="circle" hover-class="none" :ripple="true" :hair-line="false"
						:custom-style="getBtStyle('default', -1, 90, 28)" v-else @click="adequateModel = true">提交订单</u-button>
			</view>
		</view>
		<!-- 支付方式 -->
		<!-- <u-action-sheet :list="$store.state.order.paymentMethod" v-model="payTypeShow" @click="choosePayment"></u-action-sheet> -->
		<!-- <u-action-sheet :list="payList" v-model="payTypeShow" @click="choosePayment"></u-action-sheet> -->
		<!-- 余额弹窗 -->
		<u-modal v-model="balanceShow" title="请输入账户抵扣金额" @confirm="handleBalance" @cancel="cancelBalance">
			<view class="u-text-center u-p-t-30 u-p-b-30">
				<input type="digit" v-model="balance" :placeholder="'账户当前余额为'+ maxBanlance +'元'"
					placeholder-style="font-size: 28rpx;" @input="validBalance" />
			</view>
		</u-modal>
		<u-modal v-model="adequateModel" title="你现在确定提交订单吗?" @confirm="handleSubmit" >
			<view class="u-p-20 u-font-26 u-text-center">
				本订单应付款已超过剩余信用额度!<br>
				若现在提交订单销售商无法确认。建议您下单后尽快选择未支付的订单完成支付，信用额度释放后销售商才可以确认本订单
			</view>
		</u-modal>
		<!-- 活动popup -->
		<u-popup v-model="activeShow" :closeable="true" mode="bottom" >
			<activity-list v-if="activeShow" :itemList="choosePromotion" @chooseActivity="promotionChange"></activity-list>
		</u-popup>
		<!-- 运费popup -->
		<u-popup v-model="postFeeShow" :closeable="true" mode="bottom" height="550">
			<view class="box-padding" style="height: 550rpx;background-color: #FFFFFF;">
				<!-- <text class="u-font-32 text-bold" style="text-align: center;">运费规则</text> -->
				<h3 class="u-text-center u-m-b-20">运费规则</h3>
				<view class="u-flex u-row-between u-border-bottom u-p-t-30 u-p-b-30" v-if="postFeeInfo.baseValue!=0">
					<view class="u-flex">
						<view
							:style="'width: 32rpx;height:32rpx;border-radius: 50%;text-align:center;line-height:28rpx;margin-right:20rpx; background-color:'+ themeColor">
							<text style="font-size: 20rpx;">1</text>
						</view>
						<view class="u-flex-col u-row-between">
							<text class="u-font-30">起购金额</text>
							<text class="u-font-22 grey-color">满足条件允许买家下单，运费买家承担</text>
						</view>
					</view>
					<view class="u-flex u-row-right" style="text-align: right;">
						<text class="u-m-l-20" >{{ postFeeInfo.baseValue }}元</text>
					</view>
				</view>
				<view class="u-flex u-row-between u-border-bottom u-p-t-30 u-p-b-30" v-if="postFeeInfo.freeShippingValue!=0">
					<view class="u-flex">
						<view
							:style="'width: 32rpx;height:32rpx;border-radius: 50%;text-align:center;line-height:28rpx;margin-right:20rpx; background-color:'+ themeColor">
							<text style="font-size: 20rpx;">2</text>
						</view>
						<view class="u-flex-col u-row-between">
							<text class="u-font-30">包邮金额</text>
							<text class="u-font-22 grey-color">满足条件运费卖家承担，不送货上门</text>
						</view>
					</view>
					<view class="u-flex u-row-right" style="text-align: right;">
						<text class="u-m-l-20"
							>{{ postFeeInfo.freeShippingValue }}元</text>
					</view>
				</view>
				<view class="u-flex u-row-between u-p-t-30 u-p-b-30" v-if="postFeeInfo.freeDeliveryValue!=0">
					<view class="u-flex">
						<view
							:style="'width: 32rpx;height:32rpx;border-radius: 50%;text-align:center;line-height:28rpx;margin-right:20rpx; background-color:'+ themeColor">
							<text style="font-size: 20rpx;">3</text>
						</view>
						<view class="u-flex-col u-row-between">
							<text class="u-font-30">包送金额</text>
							<text class="u-font-22 grey-color">满足条件运费卖家承担且送货上门</text>
						</view>
					</view>
					<view class="u-flex u-row-right" style="text-align: right;">
						<text class="u-m-l-20"
							>{{ postFeeInfo.freeDeliveryValue }}元</text>
					</view>
				</view>
			</view>
		</u-popup>
		
		<!-- 账户余额popup -->
		<u-popup v-model="redPackageShow" :closeable="true" mode="bottom" height="900">
			<view class="box-padding" style="height: 900rpx;background-color: #FFFFFF;">
				<h3 class="u-text-center u-m-b-20">红包</h3>
				<view class="">
					<view class="u-text-center u-font-30" style="color: #999;">
						本单红包总额
					</view>
					<view class="u-text-center" style="font-size: 60rpx;font-weight: bold;">
						￥<u-count-to :start-val="startVal" :end-val="useRedPackageTotal" :duration="500" :fontSize="60" :decimals="2"></u-count-to>
					</view>
					<scroll-view scroll-y="true" style="height: 500rpx;border: 1px solid #EEEEEE;" v-if="redPackageList!=0">
						<view class="u-p-t-10 u-p-b-10 u-p-l-20 u-p-r-20" style="">
							<view class="u-m-t-40 u-m-b-40" v-for="(item,index) in redPackageList" :key="item.id">
								<view class="u-font-30" style="font-weight: bold;">
									{{item.brandOwnerName}}
								</view>
								<!-- <view class="u-font-28 u-m-t-10 u-m-b-10">
									红包余额 {{item.balance}}
								</view> -->
								<view class="u-font-28 u-flex u-m-t-30 u-m-b-20" style="border-bottom: 1px solid #eee;">
									使用余额 ￥
									 <!-- v-only-number="{max:item.availableAmount,min:0,precision:2}" -->
									<input type="number" v-model="item.useAmount" 
									placeholder="请输入使用金额"
									 style="margin-left: 20rpx;padding: 10rpx 0;"
									 @input="useAmountInputFn(item.useAmount,item.availableAmount,index)"  
									 @blur="useAmountBlurFn(item.useAmount,item.availableAmount,index)"
									 />
								</view>
								<view class="u-font-28 u-flex u-row-between">
									<view>
										可用余额 {{item.availableAmount}}
									</view>
									<view  style="color: #FF551A;" @click="useAllTotal(item.availableAmount,index)">
										全部使用
									</view>
								</view>
							</view>
						</view>
					</scroll-view>
				
					<view class="u-text-center u-font-40" style="height: 300rpx;line-height: 300rpx;color: #e2e2e2;  border: 1px solid #EEEEEE;" v-else>
						没有可用的余额
					</view>
					<button type="default" class="u-m-t-28" @click="confimRedPackageFn" style="background-color: #FFBB1A;border: none;border-radius: 60rpx;">确定</button>
				</view>
			</view>
		</u-popup>
		
		<!-- 优惠券popup -->
		<u-popup v-model="couponShow" mode="bottom" height="800">
			<view style="padding: 20rpx 20rpx;">
				<view v-for="(item,index) in couponList" :key="index"
					style="background-color: #FFFFFF;height: 200rpx;border-radius: 10rpx;box-shadow: 0px 0px 9px 1px rgba(8, 1, 3, 0.04);display: flex;margin-bottom: 30rpx;">
					<view style="flex: 1;margin-top: 45rpx; margin-left: 35rpx; position: relative;">
						<view class="u-flex u-row-left" style="align-items: baseline;">
							<view style="width: 160rpx;">
								<text v-if="item.preferentialWay == 1" style="font-size: 46rpx;"
									class="badge-color">{{ item.amount }}<text
										class="u-font-32 badge-color">元</text></text>
								<text v-if="item.preferentialWay == 2" style="font-size: 46rpx;"
									class="badge-color">{{ item.doscount }}<text
										class="u-font-32 badge-color">折</text></text>
							</view>
							<text v-if="!item.userRanges" class="u-font-32 u-m-l-20">全场通用</text>
							<text v-else class="u-font-32 u-m-l-20">部分可用</text>
						</view>
						<view style="display: flex;margin-top: 5rpx;align-items: baseline;">
							<view style="width: 160rpx;"><text
									class="u-font-22 info-color">满{{ item.thresholdAmount }}可用</text></view>
							<text v-if="!item.userRanges" class="u-font-26 info-color u-m-l-20">全场均可使用</text>
							<text v-else class="u-font-26 info-color u-m-l-20">{{ item.userRanges }}</text>
						</view>
						<view v-if="item.limitAmount && item.preferentialWay == 2"
							style="font-size: 22rpx;color:#999999;">
							最多优惠{{ item.limitAmount }}元
						</view>
						<view style="position: absolute; bottom: 20rpx;right:10rpx;font-size: 22rpx;color: #999999;">
							{{ item.expirationTime }}
						</view>
					</view>
					<view v-if="item.couponInfoId != couponId"
						style="flex-basis: 60rpx;background-color: #FFBB1A; font-size: 36rpx;text-align: center; border-radius: 0 10rpx 10rpx 0;"
						@click="useCoupon(item)">
						<view style="position:relative;top:50%;transform: translateY(-50%);">使用</view>
					</view>
					<view v-else
						style="flex-basis: 60rpx;background-color: #cccccc; font-size: 36rpx;text-align: center; border-radius: 0 10rpx 10rpx 0;">
						<view style="position:relative;top:50%;transform: translateY(-50%); color: #FFFFFF">使用中</view>
					</view>
				</view>
			</view>
		</u-popup>

		<view v-html="alipayDom"></view>
		<!-- 无发票 -->
		<u-popup v-model="addEmptyShow" class="empty-container" mode="center" :mask-close-able="false"	>
			<view >
				<view class="empty-content">
					<view class="empty-bg" >
						<view class="u-font-32" >贵公司未配置</view>
						<view class="empty-top-text"  style="">发票信息</view>
						<view class="empty-bot-btn" v-if="storeShop.managerId == storeUser.id" @click="goInvoice">立即配置</view>
						<view class="empty-bot-text" v-else>
							<view class="u-text-center u-font-32">请联系管理员配置</view>
							<view class="u-text-center u-font-32">发票信息</view>
						</view>
					</view>
				</view>
				<view class="empty-close" @click="addEmptyShow = false"></view>
			</view>
		</u-popup>
		<u-modal v-model="havePromotionShow" :content="'您有可以参加的活动可选择，是否前去选择？'" confirm-text="查看活动" cancel-text="继续提交" @confirm="showActive()" 
		@cancel="notSelectPromo()"></u-modal>
		<!--页面加载动画-->
		<akLoading isFullScreen :active="loading"></akLoading>
	</view>
</template>

<script>
	import AkAddress from '@/components/ak-order/address.vue'
	import AkOrderGoods from '@/components/ak-order/goods.vue'
	import AkInvoice from '@/components/ak-order/invoice.vue'
	import ProcessUsed from '@/components/process-used/index.vue'
	import ActivityList from './activity.vue'
	import { useShopStore } from '@/store/shop.js';
	import {useCartStore} from '@/store/cart.js';
	import {useUserStore} from '@/store/user.js';
	import { mapState } from 'pinia';
 	export default {
		components: {
			AkAddress,
			AkOrderGoods,
			AkInvoice,
			ProcessUsed,
			ActivityList
		},
		data() {
			return {
				loading: false,
				addEmptyShow:false,
				valueStyle: {
					color: this.badgeColor,
					fontWeight:'bold'
				},
				alipayDom: '',
				invoice: undefined,
				isInvoice: false,
				isElectronic: false,
				isProfessional: false,
				redPackageShow:false,
				remarks: '',
				addressInfo: {},
				postFeeInfo: {
					baseValue: 0,
					freeShippingValue: 0,
					freeDeliveryValue: 0
				},
				postFee: '运费到付',
				postFeeShow: false,
				payTypeShow: false,
				paymentMethod: null,
				maxBanlance: 0,
				balanceShow: false,
				balance: '',
				couponId: null,
				couponShow: false,
				couponList: [],
				couponAmount: 0,
				isGoPay: false,
				isGoInvoice:false,
				payList: [],
				activeShow: false,
				promotionIdList: [],
				promotionId: '',
				choosePromotion:[],
				giftList:[],
				promotionFree:0,//活动优惠金额
				promotionCount:0,//可参加活动数量
				// actualAmount:0,
				startVal:0,
				redPackageList:[],
				useRedPackageList:[],
				redBalance:0,
				sendData:{
					settlementMethod:0,
					isAdequate:true
				},
				adequateModel:false,
				havePromotionShow:false,
				notSelect:false,
			}
		},
		async onLoad() {
			uni.showLoading({
				mask: true
			})
			// this.actualAmount = this.settlementInfo.total;
			const address = await this.getShopAddress()
			if (!address) return this.$u.toast('请先配置收货地址')
			await this.getShopInvoice()
			await this.getPostFee()
			await this.getPromotion();
			uni.hideLoading()
		},
		onShow() {
			if (this.isGoPay) {
				this.$mRouter.redirectTo({
					route: '/pages/purchase/order/payresult?id=' + this.orderId
				})
			}
			// if(this.isGoInvoice){
			// 	this.getShopInvoice();
			// 	this.addEmptyShow = false;
			// }
		},
		computed: {
			useRedPackageTotal(){
				let num = 0;
				console.log(this.redPackageList);
				this.redPackageList.forEach(item=>{
					if(item.useAmount!=undefined&&item.useAmount!=0){
						num = this.addFn(num,item.useAmount)
					}
				})
				return num;
			},
			actualAmount() {
				let totalNum = this.settlementInfo.total;
				if(this.redBalance!==0){
					totalNum = this.subFn(totalNum,Number(this.redBalance))
				}
				// if(this.couponAmount!==''&&this.couponAmount!=0){
				// 	this.settlementInfo.total = this.subFn(this.settlementInfo.total,Number(this.couponAmount))
				// }
				if(this.promotionFree!==''&&this.promotionFree!=0){
					totalNum = this.subFn(totalNum,Number(this.promotionFree))
				}
				return totalNum;
			},
			...mapState(useShopStore, {storeShop: 'shop'}),
			...mapState(useCartStore, ['settlementInfo']),
			...mapState(useUserStore, {
				storeUser: 'user',
				
			}),
			
		},
		watch: {
			balance(v) {
				if (v == 0) {
					this.balance = ''
				}
			}
		},
		methods: {
			getAdequateFn(val){
				console.log(val);
				this.sendData = val;
			},
			// 活动选择后 返回数据
			promotionChange(value){
				console.log(value);
				this.promotionFree = value.reducePrice;
				this.promotionIdList = value.promotionIdList;
				this.giftList = value.itemsList;
				this.activeShow = false;//关闭活动选择弹窗
			},
			// 获取活动列表
			async getPromotion() {
				let params = {
					buyerId: this.storeShop.id,
					sellerId: this.settlementInfo.sellerShopId,
					tradeOrderItems: this.settlementInfo.shoppingCartItems,
				}
				const res = await this.$newHttp.post('api/v1.2/SalesPromotion/GetSalesPromotionByTrade', params);
				this.promotionCount = res.data.length;
				
			},
			notSelectPromo(){
				this.notSelect = true;
				this.handleSubmit();
			},
			// 获取地址信息
			async getShopAddress() {
				const res = await this.$http.get('api/Shop/GetDeliveryAddressById', {
					params: {
						ShopId: this.storeShop.id
					}
				})
				if (!res) return
				this.addressInfo = res[0]
				// this.$store.dispatch('shop/setAddressInfo', res[0])
				return res[0]
			},
			// 获取发票信息
			async getShopInvoice() {
				const res = await this.$http.get('api/Shop/GetShopInvoice', {
					params: {
						shopId: this.storeShop.id
					}
				})
				if (!res) return false;
				this.invoice = res
			},
			// 获取运费
			async getPostFee() {
				const res = await this.$http.get('api/Trade/GetPostFee', {
					params: {
						buyerId: this.storeShop.id,
						sellerId: this.settlementInfo.sellerShopId
					}
				})
				if (!res) return;
				this.postFeeInfo.baseValue = res.baseValue!=null?res.baseValue:0;
				this.postFeeInfo.freeShippingValue = res.freeShippingValue!=null?res.freeShippingValue:0;
				this.postFeeInfo.freeDeliveryValue = res.freeDeliveryValue!=null?res.freeDeliveryValue:0;
				if (res.freeShippingValue && (this.settlementInfo.total > res.freeShippingValue)) {
					this.postFee = '包邮到物流站'
				}
				if (res.freeDeliveryValue && (this.settlementInfo.total > res.freeDeliveryValue)) {
					this.postFee = '送货上门'
				}
			},
			async showPostFee() {
				this.postFeeShow = true
			},
			// 配置发票页
			goInvoice(){
				this.isGoInvoice = true;
				this.$mRouter.push({route: '/pages/purchase/shezhi/fapiao?shopId='+this.storeShop.id})
			},
			changeIsInvoice(e) {
				if (e == true && !this.invoice) {
					this.isInvoice = false
					// this.addEmptyShow = true;
					// return this.$u.toast('请先配置发票信息')
					return false;
				}
			},
			// 切换专票普票
			changeisProfessional(value) {
				this.isProfessional = value
			},
			// 获取余额
			async showBalance() {
				let params = {
					// id: this.storeShop.id,
					buyerId: this.storeShop.id,
					sellerId: this.settlementInfo.sellerShopId,
					tradeOrderItems: this.settlementInfo.shoppingCartItems,
				}
				const res = await this.$newHttp.post('api/AccountBook/GetAccountBooksByTrade', params)
				if(res.code == 200){
					this.redPackageShow = true;
					let ary = [];
					if(this.useRedPackageList.length!=0){
						res.data.forEach(item=>{
							item.useAmount = 0;
							this.useRedPackageList.forEach(options=>{
								if(item.id == options.shopAccountBookId){
									item.useAmount = options.balanceReduction;
								}
							})
							ary.push(item);
						})
						this.redPackageList = ary;
					}else{
						res.data.forEach(item=>{
							item.useAmount = 0;
							ary.push(item);
						})
						this.redPackageList = ary;
					}
				}else{
					this.$u.toast('获取红包余额失败，错误信息：'+res.erroMessage);
				}
			},
			// 使用余额的限制
			useAmountInputFn(value,maxValue,index){
				if(value>maxValue){
					this.$nextTick(function(){
						this.redPackageList[index].useAmount = Number(maxValue).toFixed(2);
					})
				}
			},
			// 使用余额的限制
			useAmountBlurFn(value,maxValue,index){
				if(value>maxValue){
					console.log(1);
					this.$nextTick(function(){
						this.redPackageList[index].useAmount = Number(maxValue).toFixed(2);
					})
				}else{
					console.log(2);
					this.$nextTick(function(){
						this.redPackageList[index].useAmount = Number(value).toFixed(2);
					})
				}
			},
			useAllTotal(maxValue,index){
				this.redPackageList[index].useAmount = Number(maxValue).toFixed(2);
			},
			// 使用红包
			confimRedPackageFn(){
				const ary = [];
				this.redPackageList.forEach(item=>{
					if(item.useAmount!=0&&item.useAmount!=undefined){
						ary.push({
							shopAccountBookId:item.id,
							balanceReduction:Number(item.useAmount)
						})
					}
				});
				this.useRedPackageList = ary;
				this.redBalance = this.useRedPackageTotal;
				this.startVal = 0;
				this.redPackageShow = false;
			},
			handleBalance() {
				if (this.balance > this.maxBanlance) {
					this.balanceShow = true
					return this.$u.toast('账户余额不足', 1000)
				}
			},
			cancelBalance() {
				if (this.balance > this.maxBanlance) {
					this.balance = ''
				}
			},
			// 账户余额变动
			validBalance(e) {
				this.balance = Number(e.detail.value)
				if (this.balance > this.maxBanlance) {
					this.balance = this.maxBanlance
				}
			},
			// 查看优惠券
			async showCoupon() {
				const list = this.settlementInfo.shoppingCartItems
				let arr = []
				for (let i = 0; i < list.length; i++) {
					arr.push({
						itemId: list[i].itemId,
						price: list[i].price,
						quantity: list[i].quantity
					})
				}
				const data = {
					shopId: this.storeShop.id,
					amount: this.settlementInfo.total,
					tardeItems: arr
				}
				if (this.couponList.length == 0) {
					const res = await this.$http.post('api/Trade/GetTardeCoupon', data)
					this.couponList = res
				}
				this.couponShow = true
			},
			useCoupon(item) {
				this.couponId = item.couponInfoId
				// 1是满减 2是打折
				if (item.preferentialWay == 1) {
					if (this.settlementInfo.total >= item.thresholdAmount) {
						this.couponAmount = item.amount
					}
				} else {
					if (this.settlementInfo.total >= item.thresholdAmount) {
						this.couponAmount = this.settlementInfo.total * (1 - item.doscount / 10).toFixed(2)
					}
				}
				this.couponShow = false
			},
			async showActive() {
				this.activeShow = true;
			},
			async choosePayment(index) {
				this.paymentMethod = this.payList[index].value
				const order = await this.generateOrder()
		
				if (this.paymentMethod == 3 || this.paymentMethod == 4) {
					let res = await this.$http.put('api/Trade/Payment', {
						id: order.id,
						paymentMethod: 4
					});
					this.$mRouter.push({
						route: '/pages/cart/offline?id=' + order.id
					});
				} else {
					this.$mRouter.push({
						route: '/pages/purchase/order/details?id=' + order.id + '&paymentMethod=' + this
							.paymentMethod
					})
				}
			},
			// 付款
			async handleSubmit() {
				if (JSON.stringify(this.addressInfo) == "{}") {
					return this.$u.toast('请先配置收货地址')
				}
				if(this.promotionCount !== 0 && this.promotionIdList.length==0&&!this.notSelect){
					this.havePromotionShow = true;
					return false;
				};
				this.loading = true
				// 判断用户是否有付款权限
				const isPayment = this.storeUser.menuCodes.includes('Payment')
				const res = await this.generateOrder()
				this.loading = false
				if(res){
					let createdTime = this.$u.timeFormat(res.createdTime,'yyyy-mm-dd hh:MM:ss')
					this.$mRouter.redirectTo({
						route: '/pages/cart/xiadan',
						query: {
							id: res.id,
							createdTime: createdTime,
							actualAmount: res.actualAmount,
							tradeNo: res.tradeNo,
							settlementMethod:res.settlementMethod,
							isPayment:isPayment,
						}
					})
				}else{
					return false;
				}
				
				// if (!isPayment) {
					// 生成待付款订单
					// const res = await this.generateOrder()
					// console.log(res)
					// this.loading = false
					// return this.$mRouter.redirectTo({
					// 	route: '/pages/gouwuche/xiadan',
					// 	query: {
					// 		id: res.id,
					// 		createdTime: res.createdTime,
					// 		actualAmount: res.actualAmount,
					// 		tradeNo: res.tradeNo,
					// 		settlementMethod:res.settlementMethod
					// 	}
					// })
				// } else {
					// 生成待付款订单
					// try {
					// 	let res = await this.$http.get('api/Shop/GetShopCollections', {
					// 		params: {
					// 			shopId: this.settlementInfo.sellerShopId
					// 		}
					// 	});
					// 	console.log(res);
					// 	this.loading = false
					// 	this.payTypeShow = true;
					// 	let payList = [];
					// 	if (res) {
					// 		res.shopCollections.forEach(item => {
					// 			if (item.shopCollectionType === 0) {
					// 				payList.push({
					// 					value: 0,
					// 					text: '微信支付'
					// 				})
					// 			}
					// 			if (item.shopCollectionType === 1) {
					// 				payList.push({
					// 					value: 11,
					// 					text: '支付宝支付'
					// 				})
					// 			}
					// 			if (item.shopCollectionType === 4) {
					// 				payList.push({
					// 					value: 3,
					// 					text: '线下支付'
					// 				})
					// 			}
					// 		});
					// 		this.payList = payList;
					// 		console.log(this.payList);
					// 	}
					// } catch (e) {
					// 	//TODO handle the exception
					// 	console.log(e);
					// 	this.loading = false
					// 	uni.showToast({
					// 		title: e
					// 	})
					// }
				// }


			},
			// 生成待付款订单
			async generateOrder() {
				let listIds = []
				const list = this.settlementInfo.shoppingCartItems.forEach(item => {
					if (item.id) {
						listIds.push({
							id: item.id
						})
					} else {
						listIds.push({
							itemId: item.itemId,
							quantity: item.quantity
						})
					}
				})
				const data = {
					buyerId: this.storeShop.id,
					sellerId: this.settlementInfo.sellerShopId,
					isInvoice: this.isInvoice,
					isElectronic: this.isElectronic,
					isProfessional: this.isProfessional,
					// balanceReduction: Number(this.balance),
					couponId: this.couponId,
					// paymentMethod: this.paymentMethod,
					remarks: this.remarks,
					tradeOrderItems: listIds,
					tradeBalanceReductions:this.useRedPackageList
				}
				if(this.promotionId!=''){
					data.promotionId = this.promotionId;
				}
				if(this.promotionIdList.length!==0){
					data.tradePromotionIds = this.promotionIdList;
				}
				const res = await this.$newHttp.post('api/v1.2/Trade/AddTrade', data);
				if (res.code === 200) {
					return res.data
				}else{
					this.$u.toast('生成订单失败,错误信息：'+res.erroMessage)
					return false;
				}
			},
			
			mulFn(a,b){
			  return this.$mHelper.mul(a,b)
			},
			addFn(a,b){
			  return this.$mHelper.add(a,b)
			},
			subFn(a,b){
			  return this.$mHelper.sub(a,b)
			},
			devFn(a,b){
			  return this.$mHelper.dev(a,b)
			},
		}
	}
</script>

<style lang="scss" scoped>
	.footer {
		position: fixed;
		bottom: 0;
		width: 100%;
		// height: 255rpx;
		background-color: #FFFFFF;
		z-index: 99;
	}

	.remark {
		background-color: #FFFFFF;
		height: 114rpx;
		// line-height: 114rpx;
		margin-bottom: 20rpx;
		padding: 0 32rpx;
		display: flex;
		align-items: center;
	}
	// 配置发票弹窗
	.empty-container{
		::v-deep .u-mode-center-box{
			background-color: transparent !important;
		}
		.empty-content{
			box-sizing: border-box;
			padding-left: 50rpx;
			.empty-bg{
				background: url('/static/order/tanchuangbg.png') no-repeat;
				width: 541rpx;
				height: 478rpx;
				background-size: 100% 100%;
				box-sizing: border-box;
				padding: 70rpx 44rpx;
				.empty-top-text{
					font-weight: bold;
					font-size: 48rpx;
					margin-top: 10rpx;
				}
				.empty-bot-btn{
					width: 252rpx;
						text-align: center;
						line-height: 90rpx;
						font-size: 32rpx;
						margin: 140rpx 0 0rpx 80rpx;
						height: 90rpx;
						background: #FFBB1A;
						box-shadow: 0px 8px 15px 3px rgba(255,187,26,0.2400);
						border-radius: 45rpx;
				}
				.empty-bot-text{
					margin: 140rpx 0 0rpx 80rpx;
					width: 252rpx;
				}
			}
		}
		.empty-close{
			background: url('/static/order/closebg.png') no-repeat;
			background-size: 100% 100%;
			width: 62rpx;
			height: 62rpx;
			margin: 60rpx auto;
		}
		
	}
	// actionsheet 操作菜单取消样式
	::v-deep .u-actionsheet-cancel {
		color: $theme-color
	}

	::v-deep .uni-easyinput__content-textarea {
		height: 40rpx;
		/* #ifndef APP-NVUE */
		min-height: 40rpx;
		max-height: 60rpx;
		/* #endif */
	}

	::v-deep .uni-easyinput__content {
		border: none;
	}

	// 优惠券弹窗背景色
	// ::v-deep .uni-scroll-view-content {
	// 	background-color: #F8F8F8;
	// }

	.scorll-container {
		::v-deep .uni-scroll-view-content {
			background-color: #fff;
		}
	}
</style>
